﻿using blackhouse.WebNemo.Business.Files;
using blackhouse.WebNemo.Business.Groups;
using blackhouse.WebNemo.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace blackhouse.WebNemo.Web {
    /// <summary>
    /// Handler do przeglądania plików
    /// </summary>
    public class NemoPreviewFile : IHttpHandler {

        #region IHttpHandler

        public void ProcessRequest(HttpContext context) {
            this.Process(context);
        }

        public bool IsReusable {
            get {
                return false;
            }
        }

        #endregion

        #region Fields

        private RecordFile file;

        #endregion

        #region Methods

        private RecordFile GetFileFromInputRequest() {
            RecordFile rf = null;
            HttpRequest request = HttpContext.Current.Request;
            string group = request["table"], column = request["column"];
            if (!String.IsNullOrEmpty(group) && !String.IsNullOrEmpty(column)) {
                int recordId = 0;
                if (Int32.TryParse(request["recordId"], out recordId)) {
                    GroupRecord record = new GroupRecord(group, recordId);
                    if (record.Exists) {
                        RecordFile file = new RecordFile(record, column);
                        if (file.Exist)
                            rf = file;
                    }
                }
            }
            return rf;
        }

        private void Process(HttpContext context) {
            this.file = this.GetFileFromInputRequest();
            if (this.file == null) {
                this.SetHeadersFor404NotFound(context.Response);
                return;
            }
            if (this.IsNotModified(this.file.FileGuid.ToString(), context.Request.Headers["If-None-Match"])) {
                this.SetHeadersForIsNotModified(context.Response);
                return;
            }
            this.SetHeadersForFile(context.Response, this.file);
            byte[] fileData = this.file.GetData();
            context.Response.BinaryWrite(fileData);
            context.Response.Flush();
        }

        private bool IsNotModified(string currentETag, string requestETag) {
            if (HttpContext.Current.Request["nocache"] == "1") return true;
            return currentETag == requestETag;
        }

        protected virtual void SetHeadersForFile(HttpResponse response, RecordFile file) {
            HeaderContentType contentType = HeaderContentType.GetFromRecordFile(file);
            contentType.SetResponseHeaders(response);
            //if(contentType.Exists)
            //    response.ContentType = contentType.GetConte
            //response.ContentType = "application/octet-stream";
            //response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", file.FileName));
            //response.AddHeader("Content-Length", file.FileSize.ToString());
            //response.AddHeader("Content-Description", "File Transfer");
            //response.AddHeader("Content-Transfer-Encoding", "binary");
        }

        private void SetHeadersFor404NotFound(HttpResponse response) {
            response.Clear();
            response.Status = "404 Not Found";
            response.StatusCode = 404;
            response.End();
        }

        private void SetHeadersForIsNotModified(HttpResponse response) {
            response.StatusCode = 304;
            response.StatusDescription = "Not Modified";
            response.Headers.Add("Content-Length", "0");
            response.End();
        }

        #endregion

    }
}